package com.ruoyi.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.gateway.constant.Constant;
import com.ruoyi.gateway.service.ISmsCodeService;
import com.ruoyi.gateway.util.ResolveBodyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

/**
 * 短信验证码
 *
 * @author : 小胖
 * @version : 0.0.1
 * @date : 2022/05/12  11:52
 **/
@Component
public class SmsCodeFilter extends AbstractGatewayFilterFactory<Object>
{
    private final static String[] VALIDATE_URL = new String[] {"/auth/register"};

    @Autowired
    private ISmsCodeService smsCodeService;

    @Override
    public GatewayFilter apply(Object config)
    {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            // 非注册请求或手机号验证码，不处理
            if ( ! StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL))
            {
                return chain.filter(exchange);
            }
            try{
                String rspStr = ResolveBodyUtil.resolveBodyFromRequest(request);
                JSONObject obj = JSONObject.parseObject(rspStr);
                //注册
                smsCodeService.checkSmsCode(obj.getString(Constant.PHONE_NUMBER), obj.getString(Constant.SMS_CODE));
            }
            catch (Exception e)
            {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
            }
            return chain.filter(exchange);
        };
    }
}
